package com.hx.mypetstore.ui.Address;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.hx.mypetstore.Bean.AddressBean;
import com.hx.mypetstore.R;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddressActivity extends AppCompatActivity {

    public static final String TAG = "地址管理界面";
    private AddAddressManageAdapter addressManagementAdapter;
    // 地址列表
    private RecyclerView mRecyclerView;
    private List<AddressBean> addressList;
    private ImageView mTitleBack;
    private TextView mTvRight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        //初始化数据
        initData();
        addressList = SPUtil.getDataList(this, SPConstants.TAG_ADDRESS_LIST, AddressBean.class);
        Log.e(TAG, "是否获取到："+addressList );
//        if (addressList.size() == 0) {
//            Intent intent = new Intent(AddressActivity.this, updateAddressActivity.class);
//            startActivity(intent);
//        }
        //初始化控件
        initViews();
        //点击事件
        clickEvent();

    }
    /**
     * 初始化数据
     */
    private void initData() {
        String url = HttpURL.GETALL;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", (String) SPUtil.get(getApplication(),SPConstants.KEY_LOCAL_USER,""))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, "地址数据"+jsonObject.toString());
                    if(!jsonObject.getBoolean("success"))
                        ;
                    else{
                        String address = jsonObject.getString("data");
                        //Json 解析对象
                        JsonParser jsonParser = new JsonParser();
                        JsonArray jsonArray = jsonParser.parse(address).getAsJsonArray();
                        //JsonArray jsonArray = jsonObject1.getAsJsonArray("msg");
                        Gson gson = new Gson();
                        ArrayList<AddressBean> list = new ArrayList<>();
                        for (JsonElement add : jsonArray) {
                            AddressBean addressBean = gson.fromJson(add, AddressBean.class);
                            list.add(addressBean);
                        }
                        Log.e(TAG, "list"+list);
                        SPUtil.saveDataList(getApplication(),SPConstants.TAG_ADDRESS_LIST,list);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        addressList = SPUtil.getDataList(this, SPConstants.TAG_ADDRESS_LIST, AddressBean.class);
        addressManagementAdapter = new AddAddressManageAdapter(addressList);
        mRecyclerView.setAdapter(addressManagementAdapter);
    }

    /**
     * 点击事件
     */
    private void clickEvent() {
        mTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddressActivity.this, updateAddressActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        // 初始化RecyclerView
        mRecyclerView = findViewById(R.id.address_list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        // 设置布局管理器
        mRecyclerView.setLayoutManager(manager);
        // 设置为垂直布局，这也是默认的
        manager.setOrientation(RecyclerView.VERTICAL);
        //返回键
        mTitleBack = findViewById(R.id.title_back);
        mTvRight = findViewById(R.id.title_right);
    }



}